<?php
declare(strict_types=1);

namespace App\WebSocketController;

use Common\Core\WebsocketCore;
use Common\Helpers\DebugHelper;
use Common\WebSocketController;
use Hyperf\Context\Context;
use Hyperf\HttpServer\Annotation\AutoController;

#[AutoController]
class AddonsController extends WebSocketController
{
    public function onMessage($server, $frame): void
    {
        DebugHelper::consoleWrite('AddonsController-进入addons','AddonsController');
        $data = $frame->data;
        $member_id  = Context::get('member_id');
        DebugHelper::consoleWrite('用户ID',[
            'member_id' => $member_id
        ]);
        $obj = new WebsocketCore(json_decode($data, true));
        $back = $obj->getStrategy();
        DebugHelper::consoleWrite('AddonsController-数据处理结果',$back);

        if ($back) {
            $server->push($frame->fd, $back);
            return;
        }

        $server->push($frame->fd, 'Recv: ' . $frame->data);
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
        // 获取调用栈信息
        $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
        DebugHelper::consoleWrite('调用栈信息', $backtrace);

        DebugHelper::consoleWrite('控制器中发生关闭事件',[
            'fd' => $fd,
            'reactorId' => $reactorId
        ]);

        var_dump('closed');
    }

    public function onOpen($server, $request): void
    {
        Context::get('sender',$server);
        $server->push($request->fd, 'Opened');
    }
}
